//
//  DetailViewController.m
//  PCNews
//
//  Created by PengchengWang on 16/3/4.
//  Copyright © 2016年 pengchengWang. All rights reserved.
//

#import "DetailViewController.h"
#import <UMSocial.h>

@interface DetailViewController ()<UIWebViewDelegate,UMSocialUIDelegate,UMSocialDataDelegate>

@property(nonatomic,strong)WKWebView *wkWebV;
///详情
@property(nonatomic,strong)NSString *content;
///详情model
@property(nonatomic,strong)BaseModel *model;
///详情title
@property(nonatomic,strong)NSString *detailTitle;

@property(nonatomic,strong)FMDatabase *myFmdb;

@property(nonatomic,strong)UIButton *btnCollect;


@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setViews];
    [self loadHtml];
    [self setCollectBtn];
}

-(instancetype)initWithDetailUrl:(NSString*)detailUrl{
    if (self = [super init]) {
        _detailUrl = detailUrl;
    }
    return self;
}

-(instancetype)initWithModel:(BaseModel*)model{
    if (self = [super init]) {
        _model = model;
    }
    return self;
}

-(void)setViews{
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight-110, kScreenWidth, 50)];
    footView.backgroundColor = [UIColor whiteColor];
    CGFloat btnWidth = kScreenWidth/10;
    CGFloat interval = kScreenWidth/10 - 5;
    UIButton *btnBack = [[UIButton alloc]initWithFrame:CGRectMake(interval, 0, btnWidth, 40)];
    UIButton *btnComment = [[UIButton alloc]initWithFrame:CGRectMake(interval*3, 0, btnWidth, 40)];
    self.btnCollect = [[UIButton alloc]initWithFrame:CGRectMake(interval*5, 0, btnWidth, 40)];
    UIButton *btnShare = [[UIButton alloc]initWithFrame:CGRectMake(interval*7, 0, btnWidth, 40)];
    UIButton *btnCopyUrl = [[UIButton alloc]initWithFrame:CGRectMake(interval*9, 0, btnWidth, 40)];
    [btnBack setBackgroundImage:[UIImage imageNamed:@"detial_buttom_back"] forState:(UIControlStateNormal)];
    [btnComment setBackgroundImage:[UIImage imageNamed:@"detial_buttom_comm"] forState:(UIControlStateNormal)];
    [btnShare setBackgroundImage:[UIImage imageNamed:@"detial_buttom_share"] forState:(UIControlStateNormal)];
    [btnCopyUrl setBackgroundImage:[UIImage imageNamed:@"detial_buttom_copy"] forState:(UIControlStateNormal)];
    [footView addSubview:btnBack];
    [footView addSubview:btnComment];
    [footView addSubview:self.btnCollect];
    [footView addSubview:btnShare];
    [footView addSubview:btnCopyUrl];
    [self.view addSubview:footView];
#pragma mark - 隐藏导航栏返回按钮
    self.navigationItem.hidesBackButton = YES;
    [btnBack addTarget:self action:@selector(btnBackAction) forControlEvents:UIControlEventTouchUpInside];
    [self.btnCollect addTarget:self action:@selector(btnCollectAction) forControlEvents:UIControlEventTouchUpInside];
    [btnCopyUrl addTarget:self action:@selector(btnCopyUrlAction) forControlEvents:(UIControlEventTouchUpInside)];
    [btnShare addTarget:self action:@selector(btnShareAction) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)btnBackAction{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)btnCollectAction{
    //1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //通过指定SQLite数据库文件路径来创建FMDatabase对象
    NSString *fileName = [doc stringByAppendingPathComponent:@"t_userCollect.sqlite"];
    self.myFmdb = [FMDatabase databaseWithPath:fileName];
    if (![self.myFmdb open]) {
        NSLog(@"数据库打开失败");
    }else{
        //创建数据库实例队列
        FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:fileName];
        [queue inDatabase:^(FMDatabase *db) {
            FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM t_userCollect where title = ?",self.model.title];
            //遍历结果
            while ([resultSet next]) {
                self.detailTitle = [resultSet stringForColumn:@"title"];
            }
            //关闭
            [resultSet close];
        }];
        if (self.detailTitle.length == 0) {
            //执行更新：除了查询都成为更新
            //创表
            BOOL createResult = [self.myFmdb executeUpdate:@"CREATE TABLE IF NOT EXISTS t_userCollect (title text NOT NULL PRIMARY KEY,model blob);"];
            /*
             对model进行归档
             */
           NSData *encodeData = [NSKeyedArchiver archivedDataWithRootObject:self.model];
            //5.插入数据库
            __block BOOL insertBool = NO;
            [queue inDatabase:^(FMDatabase *db) {
                insertBool = [db executeUpdate:@"INSERT INTO t_userCollect (title,model) VALUES (?, ?);",self.model.title, encodeData];
            }];
            if (createResult && insertBool) {
                UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"收藏成功" message:@"恭喜你收藏成功" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:alterCon animated:YES completion:nil];
                //经过几秒后执行方法
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [alterCon dismissViewControllerAnimated:YES completion:nil];
                });

            }
            else{
                UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"收藏失败" message:@"很遗憾,收藏失败" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *actionSucceed = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [alterCon addAction:actionSucceed];
                [self presentViewController:alterCon animated:YES completion:nil];
            }
        }
        else{
            
            //删除
            //判断如果要删除的组只有一个元素时,就把整个组删除
            NSString *doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
            //通过指定SQLite数据库文件路径来创建FMDatabase对象
            NSString *fileName = [doc stringByAppendingPathComponent:@"t_userCollect.sqlite"];
            FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:fileName];
            __block BOOL bDelete = NO;
            [queue inDatabase:^(FMDatabase *db) {
               bDelete = [db executeUpdate:@"DELETE FROM t_userCollect WHERE title = ?",self.detailTitle];
            }];
            if (bDelete) {
                UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"取消收藏" message:@"取消收藏成功" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:alterCon animated:YES completion:nil];
                //将标题置空,为了设置收藏按钮图片
                self.detailTitle = nil;
                [self setViews];
                //经过几秒后执行方法
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [alterCon dismissViewControllerAnimated:YES completion:nil];
                });
            }
            else{
                UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"取消失败" message:@"取消收藏失败" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:alterCon animated:YES completion:nil];
                //经过几秒后执行方法
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [alterCon dismissViewControllerAnimated:YES completion:nil];
                });
            }
        }
    }
    [self setViews];
    [self setCollectBtn];
}

-(void)btnShareAction{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:kUMKey
                                      shareText:@"友盟社会化分享让您快速实现分享等社会化功能，http://umeng.com/social"
                                     shareImage:[UIImage imageNamed:@"icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
}

-(void)btnCopyUrlAction{
#pragma mark - 将一段文字复制到系统剪切板上
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    NSString *strCopyUrl = [NSString stringWithFormat:@"%@ http://m.mydrivers.com/newsview.aspx?id=%ld&cid=1",self.model.title,self.model.id];
    pasteboard.string = strCopyUrl;
    UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:@"已复制该新闻标题,URL地址" message:strCopyUrl preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alterCon animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alterCon dismissViewControllerAnimated:YES completion:nil];
    });
}

-(void)loadHtml{
    self.wkWebV = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-110)];
    self.wkWebV.scrollView.directionalLockEnabled = YES;
    self.wkWebV.scrollView.showsHorizontalScrollIndicator = NO;
    self.wkWebV.backgroundColor =[UIColor whiteColor];
    [self.wkWebV setOpaque:NO];
    [self.view addSubview:self.wkWebV];
    if (self.detailUrl) {
        [self setWebViewWithUrl];
    }else{
        [self setWebView];
    }
}

-(void)setWebViewWithUrl{
    [URLRequestManager requestUrlWithType:GET strURL:self.detailUrl condition:nil success:^(id item) {
        NSArray * tempArray =item;
        NSDictionary * dic =tempArray[0];
        [self.model setValuesForKeysWithDictionary:dic];
        [self setWebView];
    } faile:^(NSError *error) {
    }];
}

-(void)setWebView{
    NSString *cssFilePath;
    cssFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"css_Detail.html"];
    NSString *cssString=[NSString stringWithContentsOfFile:cssFilePath encoding:NSUTF8StringEncoding error:nil];
    NSString *htmlStr = [NSString stringWithFormat:@"<!DOCTYPE HTML><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"format-detection\" content=\"telephone=no\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"><title>新闻</title></head>%@ <body style=\"margin:0px; padding:0px;\"><center><div  class=\"marRight10 marLeft10 marTop6 atitle \"> %@</div><div  style=\"display:inline;\" class=\"marLeft10 atime\">%@</div>&nbsp;&nbsp;<div  style=\"display:inline;\" class=\"marRight10 atime\">%@</div></center><div style=\"margin-top:4px;margin-bottom:4px;\" ><hr/></div><div  class=\"content\">%@</div></body></html>",cssString,self.model.title, self.model.postdate, self.model.editor,self.model.content];
    [self.wkWebV loadHTMLString:htmlStr baseURL:nil];
    [self setCollectBtn];
}

-(void)setCollectBtn{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //通过指定SQLite数据库文件路径来创建FMDatabase对象
    NSString *fileName = [doc stringByAppendingPathComponent:@"t_userCollect.sqlite"];
    self.myFmdb = [FMDatabase databaseWithPath:fileName];
    if (![self.myFmdb open]) {
        NSLog(@"数据库打开失败");
    }else{
        //创建数据库实例队列
        FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:fileName];
        [queue inDatabase:^(FMDatabase *db) {
            FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM t_userCollect where title = ?",self.model.title];
            //遍历结果
            while ([resultSet next]) {
                self.detailTitle = [resultSet stringForColumn:@"title"];
            }
            //关闭
            [resultSet close];
        }];
        if (self.detailTitle.length == 0) {
            [self.btnCollect setBackgroundImage:[UIImage imageNamed:@"detial_buttom_collect"] forState:(UIControlStateNormal)];
        }
        else{
            [self.btnCollect setBackgroundImage:[UIImage imageNamed:@"detial_buttom_collected"] forState:(UIControlStateNormal)];
        }
    }
}

-(BaseModel *)model{
    if (!_model) {
        _model = [[BaseModel alloc]init];
    }
    return _model;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - N  avigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
